package com.grgbanking.it.project.controller;


import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.grgbanking.it.common.json.JSONHelper;
import com.grgbanking.it.common.util.DateUtil;
import com.grgbanking.it.project.component.WXProjectConstant;
import com.grgbanking.it.project.entity.Task;
import com.grgbanking.it.project.entity.TaskResult;
import com.grgbanking.it.project.service.ITaskService;
import com.grgbanking.it.system.entity.User;
import com.grgbanking.it.system.service.IDepartmentService;
import com.grgbanking.it.system.service.IUserService;
import com.grgbanking.it.wx.entity.WXPassiveMessage;
import com.grgbanking.it.wx.entity.WXVerify;

/**
 * 微信日常工作入口
 * 
 * WXDailyTaskController
 * 
 * @author 潘广伟
 * @Email p_3er@qq.com
 * @Date 2015-1-20 上午8:45:52
 * 
 * @version 1.0.0
 *
 */
@Controller
@RequestMapping("/wx/task")
public class WXTaskController {
	private Integer agentId = WXProjectConstant.DAILY_AGENT_ID;
	@Autowired
	private ITaskService taskService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IDepartmentService departmentService;
	
	/**
	 * 回调接口校验
	 * apiWhenGet
	 * 
	 * @param verify
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@ResponseBody  
	@RequestMapping(value="api",method=RequestMethod.GET)
	public String apiWhenGet(WXVerify verify){  
		String echo = "error";
		try {
			echo =  taskService.getEcho(verify);
		} catch (Exception e) {
			e.printStackTrace();
		}  
		
		return echo;
	}   
	
	/**
	 * 信息接收入口
	 * apiWhenPost
	 * 
	 * @param request
	 * @param verify
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value="api", method = RequestMethod.POST)  
    public void apiWhenPost(HttpServletRequest request,HttpServletResponse response,WXVerify verify){ 
		try {
			String backMsg = null;
			
			//从请求中读取整个post数据  
			InputStream inputStream = request.getInputStream();  
	        String postData = IOUtils.toString(inputStream, "UTF-8");  
	        verify.setPostData(postData);
	       
	        WXPassiveMessage recivedMessage = taskService.reciveMsg(verify);
	        if(recivedMessage.getAgentID() == agentId){
	        	
	        }
	        if(backMsg != null){
	        	response.setCharacterEncoding("UTF-8");
	 	        response.getWriter().print(backMsg);
	        }
	       
		} catch (Exception e) {
			e.printStackTrace();
		}  

    }  
	/**
	 * 微信菜单入口
	 * 
	 * menu
	 * 
	 * @param code
	 * @param state
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("{type}")
	public ModelAndView menu(@PathVariable("type") String type,HttpServletRequest request, String code,Integer state){
		ModelAndView view = new ModelAndView();
		try {
			User user = userService.getUserByCode(code,agentId);
			if(user == null){
				view.setViewName("redirect:/wx/error.jsp");
			}else{
				request.setAttribute("user", user);

				if(type.equals("task")){
					view.setViewName("/wx/task/task.jsp");
				}else if(type.equals("daily_new")){
					view.setViewName("/wx/task/daily_new.jsp");
				}else if(type.equals("plan_new")){
					view.setViewName("/wx/task/plan_new.jsp");
				}else if(type.equals("task_today")){
					request.setAttribute("date", DateUtil.getInstance().today("yyyy-MM-dd"));
					request.setAttribute("isBack", 0);
					view.setViewName("/wx/task/task_daily.jsp");
				}else if(type.equals("team_today")){
					request.setAttribute("date", DateUtil.getInstance().today("yyyy-MM-dd"));
					request.setAttribute("isBack", 0);
					view.setViewName("/wx/task/task_team.jsp");
				}else if(type.equals("team_yesterday")){
					request.setAttribute("date", DateUtil.getInstance().yesterday("yyyy-MM-dd"));
					request.setAttribute("isBack", 0);
					view.setViewName("/wx/task/task_team.jsp");
				}else if(type.equals("team_search_task")){
					request.setAttribute("date", DateUtil.getInstance().yesterday("yyyy-MM-dd"));
					request.setAttribute("isBack", 0);
					view.setViewName("/wx/task/task_team_search.jsp");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return view; 
	}
	
	
	/************************************页面跳转及任务处理相关********************************************/
	
	
	/**
	 * 页面跳转
	 * page
	 * 
	 * @param page
	 * @param userId
	 * @param request
	 * @param date
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value="{page}/{userId}",method=RequestMethod.GET)
	public ModelAndView page(@PathVariable("page") String page,@PathVariable("userId")String userId,String keyword,HttpServletRequest request){
		ModelAndView view = new ModelAndView();
		try {
			User user = userService.getUserByUsername(userId);
			if(user == null){
				view.setViewName("redirect:/wx/error.jsp");
			}else{
				request.setAttribute("user", user);
				
				if(page.equals("task_daily")){
					request.setAttribute("date", keyword);
					view.setViewName("/wx/task/task_daily.jsp");
				}else if(page.equals("task_team")){
					request.setAttribute("date", keyword);
					view.setViewName("/wx/task/task_team.jsp");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return view; 
	}
	/**
	 * 加载用户任务
	 * loadTasks
	 * 
	 * @param type 1 个人日历  2 查询个人 3 根据个人账号查询部门 4根据部门编号查询部门  
	 * @param id
	 * @param start
	 * @param end
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@ResponseBody  
	@RequestMapping(value="load/{type}/{id}",method=RequestMethod.GET)
	public Object loadTasks(@PathVariable("type")Integer type,@PathVariable("id")String id,String start,String end){  
		String json = null;
		try {
			if(type == 1){
				json = taskService.findJsonForCalender(start, end, id);
			}else if(type == 2){
				json = taskService.findByDaily(start, id);
			}else if(type == 3){
				json = taskService.findToTeam(start, id);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			json = JSONHelper.getExceptionMessage(e);
		}  
		return json;  
	} 
	/**
	 * 获取团队人员信息
	 * getTeam
	 * 
	 * @param type
	 * @param id
	 * @param start
	 * @param end
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@ResponseBody  
	@RequestMapping(value="team/origanization/{id}",method=RequestMethod.GET)
	public Object getTeam(@PathVariable("id")Integer id){  
		String json = null;
		try {
			json = departmentService.getChildren(id);
		} catch (Exception e) {
			e.printStackTrace();
			json = JSONHelper.getExceptionMessage(e);
		} 
		return json;  
	} 
	
	/**
	 * 新的任务
	 * newTask
	 * 
	 * @param userId
	 * @param type 1 项目任务  2 日常工作  3 个人计划 4 领导分配
	 * @param task
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value="new/{type}/{userId}",method=RequestMethod.POST)
	public ModelAndView newTask(@PathVariable("userId")String userId,@PathVariable("type")Integer type,Integer isContinue,Task task,HttpServletRequest request){
		ModelAndView view = new ModelAndView();
		try {
			User user = userService.getUserByUsername(userId);
			task.setCreator(userId);
			task.setUsername(userId);
			task.setTrueName(user.getUserName());
			task.setDepartmentId(user.getDeptId());
			task.setDepartmentName(user.getDepartment().getDeptName());
			task.setType(type);
			taskService.saveOrUpdate(task);
			
			if(isContinue == 1){
				request.setAttribute("user", user);
				if(type == 2){
					view.setViewName("/wx/task/daily_new.jsp");
				}else if(type == 3){
					view.setViewName("/wx/task/plan_new.jsp");
				}
				
			}else{
				view.setViewName("redirect:/wx/success.jsp");
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return view; 
	}
	/**
	 * 处理任务
	 * 
	 * execudeTask
	 * 
	 * @param type 1 直接完成 2延期到明天 3填写处理过程 4取消
	 * @param userId
	 * @param task
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@ResponseBody  
	@RequestMapping(value="execute_{type}/{userId}/{taskId}",method=RequestMethod.POST)
	public Object executeTask(@PathVariable("type")Integer type,@PathVariable("userId")String userId,@PathVariable("taskId")Integer taskId,TaskResult taskResult){
		String json = null;
		try {
			User user = userService.getUserByUsername(userId);
			if(user != null){
				if(type == 1){
					taskService.updateDirectFinish(taskId);
				}else if(type == 2){
					taskService.updatePostponeToTomorrow(taskId);
				}else if(type == 3){
					taskService.updateHandle(taskId, taskResult);
				}else if(type == 4){
					taskService.delete(taskId);
				}
			}
			
			json = "操作成功";
		} catch (Exception e) {
			e.printStackTrace();
			json = JSONHelper.getErrorMsg(e);
		}
		
		return json;
	}
	
}
